import 'package:get/get.dart';

import '../../../data/models/recent_closing_price_model.dart';
import '../../../core/network/bao_stock_service.dart';


class RecentClosingPriceController extends GetxController {
  final RxList<RecentClosingPrice> recentClosingPriceList =
      <RecentClosingPrice>[].obs;
  final RxString statusMessage = ''.obs;
  final RxBool isLoading = false.obs;
  final RxString stockCode = 'sh.603161'.obs;

  void updateStockCode(String code) {
    stockCode.value = code;
  }

  @override
  void onClose() {
    super.onClose();
  }

  Future<void> fetchStockData() async {
    isLoading.value = true;
    statusMessage.value = '正在获取股票数据...';

    try {
      // 计算日期：获取最近10天数据
      final endDate = DateTime.now();
      final startDate = endDate.subtract(const Duration(days: 20));

      // 使用 BaoStockService 查询数据
      final baoStockService = Get.find<BaoStockService>();
      final data = await baoStockService.queryHistoryKData(
        stockCode.value,
        _formatDate(startDate),
        _formatDate(endDate),
      );

      // 只取最近10条数据
      final recentData = data.length > 10 ? data.sublist(0, 10) : data;

      recentClosingPriceList.value = recentData;
      statusMessage.value = '获取成功，共${recentData.length}条数据';

    } catch (e) {
      statusMessage.value = '获取数据失败: $e';
      print('获取数据错误: $e');
    } finally {
      isLoading.value = false;
    }
  }

  // 添加日期格式化方法
  String _formatDate(DateTime date) {
    return "${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
  }
}